<template>
  <div class="app-container">
    <div class="form-container">
      <div class="filter-view">
        <el-form ref="form" label-width="100px">
          <el-form-item label="项目更新时间">
            <el-row>
              <el-col :span="10" :xs="24" :sm="24" :md="10" class="mb5">
                <el-date-picker
                  v-model="queryParams.beginDateTime"
                  placeholder="选择开始时间"
                  style="width: 40%;"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
                至
                <el-date-picker
                  v-model="queryParams.endDateTime"
                  :default-time="'23:59:59'"
                  placeholder="选择结束时间"
                  style="width: 40%;"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                />
              </el-col>
              <el-col :span="14" :xs="24" :sm="24" :md="14">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入项目名称"
                  class="project_my_input_search"
                  style="width: 40%;"
                  type="text"
                />
                <el-button class="ml-20" icon="el-icon-search" type="primary" style="border-bottom-left-radius: 0; border-top-left-radius: 0;" @click="search()">
                  查询
                </el-button>
                <el-button class="ml-20 el-button--cyan" icon="el-icon-folder-add" @click="createFolderVisible=true">
                  创建文件夹
                </el-button>
                <el-button class="ml-20" icon="el-icon-plus" type="success" @click="createFormVisible=true">
                  创建问卷
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="项目状态">
                <el-radio-group v-model="queryParams.status" size="small" @change="()=>{
                  queryParams.current=0
                  queryProjectPage()}"
                >
                  <el-radio-button v-for="status in projectStatusList" :key="status.code" :label="status.code">
                    {{ status.name }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="问卷类型">
                <el-radio-group v-model="queryParams.type" size="small" @change="()=>{
                  queryParams.current=0
                  queryProjectPage()}"
                >
                  <el-radio-button v-for="status in projectTypeList" :key="status.code" :label="status.code">
                    {{ status.name }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <el-button-group>
                  <el-button :type="$store.state.form.dataShowType=='table'?'primary':'default'" size="mini"
                             @click="handleDataShowType('table')"
                  >
                    <font-icon
                      class="fas  fa-th-list"
                    />
                  </el-button>
                  <el-button :type="$store.state.form.dataShowType=='card'?'primary':'default'" size="mini"
                             @click="handleDataShowType('card')"
                  >
                    <font-icon
                      class="fas fa-th-large "
                    />
                  </el-button>
                </el-button-group>
                <el-button style="margin-left:20px" type="primary" size="mini" :export-loading="exportLoading" @click="handleExport">
                  导出统计数据
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="form-breadcrumb">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item @click.native="getFolderForm(0)">
            我的问卷
          </el-breadcrumb-item>
          <el-breadcrumb-item v-for="b in breadcrumbList" :key="b.id">
            {{ b.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <form-card-list
        v-if="$store.state.form.dataShowType=='card'"
        v-loading="projectListLoading"
        :project-list.sync="projectList"
        :current-page="queryParams.current"
        @enterFolder="handleEnterFolder"
        @move="handleOpenMoveFolderDialog"
        @refresh="queryProjectPage"
        @downLoadFolder="handleDownLoadFolder"
        @downLoad="handleDownload"
        @renameFolder="handleRenameFolderDialog"
      />
      <my-form-table
        v-if="$store.state.form.dataShowType=='table'"
        v-loading="projectListLoading"
        :project-list.sync="projectList"
        :current-page="queryParams.current"
        @enterFolder="handleEnterFolder"
        @move="handleOpenMoveFolderDialog"
        @downLoadFolder="handleDownLoadFolder"
        @downLoad="handleDownload"
        @refresh="queryProjectPage"
        @renameFolder="handleRenameFolderDialog"
      />
      <div class="project-page-view">
        <el-pagination
          v-if="total>10"
          :current-page.sync="queryParams.current"
          :page-size.sync="queryParams.size"
          :total="total"
          background
          layout="total, prev, pager, next"
          @current-change="queryProjectPage"
        />
      </div>
    </div>
    <el-dialog
      :visible.sync="createFormVisible"
      title="创建问卷"
      width="30%"
    >
      <el-form ref="createForm" :model="formData" label-width="100px">
        <el-form-item
          :rules="[
            { required: true, message: '名称不能为空'} ]"
          label="名称"
          prop="name"
        >
          <el-input v-model="formData.name" autocomplete="off" />
        </el-form-item>
        <el-form-item
          :rules="[
            { required: true, message: '类型不能为空'} ]"
          label="类型"
          prop="type"
        >
          <el-radio-group v-model="formData.type">
            <el-radio label="1">
              普通问卷
            </el-radio>
            <el-radio label="2">
              流程问卷
            </el-radio>
            <el-radio label="4">
              考试
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="描述"
          prop="description"
        >
          <el-input v-model="formData.description"
                    autocomplete="off" type="textarea"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="requestLoading.pushFormData" @click="createFormHandle">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="createFolderVisible"
      title="创建文件夹"
      width="30%"
    >
      <el-form ref="createFolder" :model="folderData" label-width="100px">
        <el-form-item
          :rules="[
            { required: true, message: '文件夹名称不能为空'} ]"
          label="名称"
          prop="name"
        >
          <el-input v-model="folderData.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="createFolderVisible = false">取 消</el-button>
        <el-button type="primary" :loading="requestLoading.pushFolderData" @click="createFormFolderHandle">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="folderTreeVisible"
      title="移动到文件夹"
      width="30%"
    >
      <el-tree ref="folderTree" :data="folderTreeData" :props="folderTreeProps"
               check-strictly
               highlight-current
               node-key="id"
               show-checkbox
               default-expand-all
               @check-change="handleFolderTreeChange"
      >
        <span slot-scope="{ node }" class="custom-tree-node">
          <i class="iconfont icon-wenjianjia" />
          <span class="mp5">{{ node.label }}</span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="folderTreeVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleMoveFolder">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :visible.sync="renameFolderVisible"
      title="重命名文件夹"
      width="30%"
    >
      <el-form ref="renameFolder" :model="folderData" label-width="100px">
        <el-form-item
          :rules="[
            { required: true, message: '文件夹名称不能为空'} ]"
          label="名称"
          prop="name"
        >
          <el-input v-model="folderData.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="renameFolderVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRenameFolder">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 导出数据 -->
    <el-dialog
      :visible.sync="downloadFormVisible"
      title="导出数据"
      width="30%"
      @close="resetForm('downloadForm')"
    >
      <el-form ref="downloadForm" :model="downloadForm" label-width="100px">
        <el-form-item
          label="文件名"
          prop="filename"
        >
          <el-input v-model="downloadForm.filename" autocomplete="off" />
        </el-form-item>
        <el-form-item
          label="保存类型"
          prop="type"
        >
          <el-select v-model="downloadForm.type" placeholder="请选择">
            <el-option
              v-for="item in types"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          label="标题"
          prop="sheetName"
        >
          <el-input v-model="downloadForm.sheetName" autocomplete="off" />
        </el-form-item> -->
        <el-form-item
          label="选择数据"
          prop="mode"
        >
          <el-select v-model="downloadForm.mode" placeholder="请选择">
            <el-option
              v-for="item in dataTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item
          label="选择字段"
          prop="columns"
        >
          <div class="checkWrap">
            <div class="checkHeader">
              <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="handleCheckAllChange">
                全选
              </el-checkbox>
            </div>
            <div class="checkBody"> 
              <div style="margin: 15px 0;" />
              <el-checkbox-group v-model="downloadForm.columns" @change="handleCheckedChange">
                <el-checkbox v-for="item in allField" :key="item.value" :label="item.value" :value="item.value">
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="downloadFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="downloadLoading" @click="exportHandle">导 出</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {createFormRequest, getUserFormFolderTreeRequest, pageFormRequest, updateFormRequest,exportAllSample} from '@/api/project/form'
import FormCardList from "./card"
import mixin from "./mixin"
import MyFormTable from "./table"
import {jsonSimpleClone} from "../../../utils"
import _cloneDeep from 'lodash/cloneDeep'
import {listFormFieldsRequest} from "@/api/project/form"
import {exportDataRequest,batchExportData,batchExportDataPath} from "@/api/project/data"

import {getFormReportRequest} from "@/api/project/report"
import { Session } from '@/utils/storage.js'
export default {
  name: 'MyProject',
  components: {
    MyFormTable,
    FormCardList
  },
  mixins: [mixin],
  data() {
    return {
      createFolderVisible: null,
      createFormVisible: null,
      folderTreeVisible: null,
      renameFolderVisible: null,
      dataShowType: 'table',
      total: 0,
      queryParams: {
        current: 1,
        size: 12,
        name: '',
        beginDateTime: null,
        endDateTime: null,
        status: null,
        folderId: 0
      },
      formData: {
        description: '',
        name: '问卷名称'
        // type: "1"
      },
      folderData: {
        name: '文件夹名称',
        type: 3,
        folder: true,
        formKey: '',
        folderId: 0
      },
      breadcrumbList: [],
      projectList: [],
      projectListLoading: true,
      // 文件夹
      folderTreeData: [],
      folderTreeProps: {
        children: 'children',
        label: 'name'
      },
      pageCurrent: '',
      requestLoading: { // 请求加载中状态
        pushFormData: false,
        pushFolderData: false
      },
      exportLoading:false,
      currentFolder:{},
      types:[
        {
          label:'Excel 工作簿(*.xlsx)',
          value:'xlsx'
        }
      ],
      dataTypes:[
        // {
        //   label:'当前数据（当前页的数据）',
        //   value:'current'
        // },
        // {
        //   label:'选中数据（当前页选中的数据）',
        //   value:'selected'
        // },
        {
          label:'全量数据（包括所有分页的数据）',
          value:'all'
        }
      ],
      downloadFormVisible:false,
      downloadForm:{
        filename: '',
        mode: 'all',
        sheetName: '',
        type: 'xlsx',
        columns:[]
      },
      allField:[],
      allFieldLabel:[],
      isIndeterminate: false,
      checkAll:true,
      formKey:'',
      downloadLoading:false,
      selectRow:{}
    }
  },
  destroyed() {
    console.log(Session.get('tagsViewList'),'1111')
    if(Session.get('tagsViewList')){
      var arr = Session.get('tagsViewList').filter((item) => {
        return item.path=="/project/my"
      })
    
      if(!arr.length){
          this.$store.dispatch('form/setCurrentFormFolder', null)
          this.$store.dispatch('form/setCurrentPage', 1)
          this.$store.dispatch('form/setDataShowType', 'table')
      }
      console.log(this.$store.state.form.currentPage,'this.$store.state.form.currentPage')
      console.log(arr.length,'8888')
    }else{
          this.$store.dispatch('form/setCurrentFormFolder', null)
          this.$store.dispatch('form/setCurrentPage', 1)
          this.$store.dispatch('form/setDataShowType', 'table')
    }
    
  },
  created() { 
    // 上次进入的文件夹 避免进入编辑丢失
    let f = this.$store.state.form.currentFormFolder
    if (f) {
      this.queryParams.current = this.$store.state.form.currentFormFolder ? (this.$store.state.form.currentPage ? this.$store.state.form.currentPage : 1) : 1
      this.handleEnterFolder(f)
    } else {
      this.queryParams.current = this.$store.state.form.currentPage ? this.$store.state.form.currentPage : 1
      this.queryProjectPage()
    }
    
  },
  methods: {
    handleDataShowType(flag){
      this.$store.dispatch('form/setDataShowType', flag)
    },
    handleExport(){
      this.$confirm('是否确认导出数据?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true
        return exportAllSample({
          folderId:this.queryParams.folderId,
          userId:this.$store.getters.userId
        }).then((res) => {
          this.download(res, this.queryParams.folderId ==0 ? '问卷系统2022年度HN企业满意度调查' : '问卷系统2022年度HN企业满意度调查—'+this.currentFolder.name)
          this.exportLoading = false
        }).catch(() => {
          this.exportLoading = false
        })
      })
    },
    createFormHandle() {
      this.$refs['createForm'].validate((valid) => {
        if (valid) {
          // 默认创建到当前打开文件夹
          this.formData.folderId = this.queryParams.folderId || 0
          this.requestLoading.pushFormData = true
          this.formData.description = this.formData.description ? this.formData.description : '为了给您提供更好的服务，希望您能抽出几分钟时间，将您的感受和建议告诉我们，我们非常重视每位 用户的宝贵意见，期待您的参与！现在我们就马上开始吧！'
          createFormRequest(this.formData).then((res) => {
            console.log(this.queryParams.current,'this.queryParams.current')
            this.toProjectHandle(res.data, 'editor',this.queryParams.current)
            this.requestLoading.pushFormData = false
          }).catch(() => {
            this.requestLoading.pushFormData = false
          })
        } else {
          return false
        }
      })
    },
    createFormFolderHandle() {
      this.$refs['createFolder'].validate((valid) => {
        if (valid) {
          this.folderData.type = 3
          this.folderData.folder = true
          this.requestLoading.pushFolderData = true
          createFormRequest(this.folderData).then((res) => {
            this.requestLoading.pushFolderData = false
            this.msgSuccess('创建成功')
            this.queryProjectPage()
            this.createFolderVisible = null
          }).catch(() => {
            this.requestLoading.pushFolderData = false
            this.msgSuccess('创建失败，请稍后重试。')
          })
        } else {
          return false
        }
      })
    },
    search(){
      this.queryParams.current=1
      this.queryProjectPage()
      },
    queryProjectPage() {
      pageFormRequest(
        this.queryParams
      ).then((res) => {
        let {records, total, size} = res.data
        this.projectList = records
        this.total = total
        this.queryParams.size = size
        this.projectListLoading = false
      })
    },
    handleOpenMoveFolderDialog(item) {
      this.folderTreeVisible = true
      this.folderData = item
      getUserFormFolderTreeRequest().then((res) => {
        this.folderTreeData = [{id: 0, name: '根目录', children: res.data}]
      })
    },
    handleRenameFolderDialog(item) {
      this.renameFolderVisible = true
      this.folderData = jsonSimpleClone(item)
    },
    handleFolderTreeChange(data, checked, node) {
      if (checked) {
        this.$refs.folderTree.setCheckedNodes([data])
      }
    },
    handleMoveFolder() {
      if (!this.$refs.folderTree.getCheckedKeys().length > 0) {
        this.msgWarning('请选择文件夹')
        return
      }
      let folderId = this.$refs.folderTree.getCheckedKeys()[0]
      this.folderData.folderId = folderId
      updateFormRequest(this.folderData).then((res) => {
        this.msgSuccess('移动成功')
        this.folderTreeVisible = false
        this.queryProjectPage()
      })
    },
    /**
     * 重新命名文件夹
     */
    handleRenameFolder() {
      updateFormRequest(this.folderData).then((res) => {
        this.msgSuccess('修改成功')
        this.renameFolderVisible = null
        this.folderData = {}
        this.queryProjectPage()
      })
    },
    handleEnterFolder(f) {
      console.log(f,'f----')
      this.currentFolder=f
      this.breadcrumbList.push(f)
      this.$store.dispatch('form/setCurrentFormFolder', f)
      this.getFolderForm(f.id)
    },
    /**
     * 查询文件夹下的问卷
     * @param id
     */
    getFolderForm(id) {
      this.queryParams.folderId = id
      this.folderId = id
      if (id == 0) {
        this.breadcrumbList = []
        this.$store.dispatch('form/setCurrentFormFolder', '')
        this.$store.dispatch('form/setCurrentPage', 1)
        this.queryParams.current=1
      }
      console.log(this.$store.state.form.currentFormFolder,'currentFormFolder---')
      console.log(this.$store.state.form.currentPage,'currentPage---')
      console.log(id,'folderId---')
      this.queryProjectPage()
    },
    // 下载文件夹
    handleDownLoadFolder(row){
      
      this.$confirm('是否确认导出?', '导出', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        // return batchExportData({
        //   folderId:row.id,
        // }).then((res) => {
        //   this.download(res, row.name,'.zip')
        // })
        return batchExportDataPath({
          folderId:row.id,
        }).then((res) => {
          let url = res.data
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', row.name + '.zip')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
          // this.download(res, row.name,'.zip')
        })
        
      })
    },
    // 下载
    handleDownload(row){
      this.selectRow = row
      this.formKey=row.formKey
      if (this.downloadForm.mode === 1) {
          listFormFieldsRequest(row.formKey).then((res) => {
           this.allField=res.data
           this.allFieldLabel=[]
           res.data.forEach((item) =>{
              this.allFieldLabel.push(item.value)
           })
           this.downloadFormVisible=true
           this.checkAll=true
           this.downloadForm.columns = this.allFieldLabel
          })
        } else {
          listFormFieldsRequest(row.formKey).then((res) => {
            this.allField=res.data
            this.allFieldLabel=[]
            res.data.forEach((item) =>{
                this.allFieldLabel.push(item.value)
            })
            this.downloadFormVisible=true
            this.checkAll=true
            this.downloadForm.columns = this.allFieldLabel
          })
        }
    },
    exportHandle(){
      console.log(this.downloadForm.columns,'downloadForm.columns')
      this.downloadLoading=true
      let params = {
        columns: this.downloadForm.columns,
        filename: this.downloadForm.filename,
        mode: this.downloadForm.mode,
        sheetName: this.downloadForm.sheetName ? this.downloadForm.sheetName : '问卷数据',
        type: this.downloadForm.type,

        formKey: this.formKey,
        filter: {},
        authGroupId: '',
        checkboxIds: [],
        }
      exportDataRequest({
        formKey: this.formKey,
      }).then((res) => {
        this.downloadLoading=false
        this.downloadFormVisible = false
       
        var fileName = this.downloadForm.filename ? this.downloadForm.filename : this.selectRow.textName
        console.log(fileName,'fileName')
        let url = res.data
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', fileName + (this.downloadForm.type == "csv" ? '.csv' : '.xlsx'))
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
        
        // if (this.downloadForm.type == "csv") {
        //   this.download(response, fileName, ".csv")
        // } else {
        //   this.download(response, fileName)
        // }
      }).catch(() => {
          this.downloadLoading = false
        })
    },
    resetForm(formName) {
      this.isIndeterminate= false
      this.$refs[formName].resetFields()
    },
    handleCheckAllChange(val) {
      this.downloadForm.columns = val ? this.allFieldLabel : []
      this.isIndeterminate = false
    },
    handleCheckedChange(value) {
      let checkedCount = value.length
      this.checkAll = checkedCount === this.allField.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allField.length
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  //display: flex;
  width: 100%;
  height: 100%;
  //flex-direction: column;
  //align-items: center;
  //align-content: center;
}

.form-container {
  width: 1280px;
  margin: 0 auto;
}


.project-page-view {
  margin-top: 30px;
  text-align: center;
}

.form-breadcrumb {
  margin: 10px 50px 10px 0px;
}

::v-deep .el-breadcrumb__inner {
  cursor: pointer !important;
}
.checkWrap{
  border: 1px solid #dcdfe6;
  margin: 3px 0;
  border-radius: 4px;
}
.checkHeader{
    padding: 0.2em 1em 0.2em 1em;
    background-color: #f8f8f9;
    font-weight: 700;
    border-bottom: 1px solid #e8eaec;
}
.checkBody{
    padding: 0.2em 1em 0.2em 1em;
    min-height: 10em;
    max-height: 17.6em;
    overflow: auto;
}
.checkBody .el-checkbox{
  width:100%
}
</style>

<style lang="scss">
.project_my_input_search {
  width: auto;
  .el-input__inner {
    border-bottom-right-radius: 0px !important;
    border-top-right-radius: 0px !important;
  }
}
</style>
